import { Body, Controller, Get, Injectable, OnModuleDestroy, OnModuleInit, Post } from "@nestjs/common";
import kafka from 'kafka-node'
import { MsgService } from "./msg.service";
import { Kafka, logLevel, Producer } from 'kafkajs'

@Controller('receiver')
export class GeweReceiverController implements OnModuleInit, OnModuleDestroy {
    producerGewe: Producer = null

    kafkaHost: string = '134.175.224.228:9092'

    constructor(
        private msgService: MsgService
    ) { }

    async onModuleInit() {

        const kafka = new Kafka({
            logLevel: logLevel.INFO,
            brokers: [`${this.kafkaHost}`],
            clientId: 'kafka-receiver',
        })

        this.producerGewe = kafka.producer({
            allowAutoTopicCreation: true,
            transactionTimeout: 30000
        })

        await this.producerGewe.connect()

        // setInterval(async () => {
        //     let msg = await this.msgService.generateMessage()
        //     msg.Data.MsgSeq = Date.now()
        //     let payloads: kafka.ProduceRequest[] = [
        //         { topic: 'latestMsgToRedis', messages: JSON.stringify(msg), key: Date.now().toString() },
        //     ];

        //     //发送到存储队列{
        //     producerGewe.send({
        //         topic: 'latestMsgToRedis',
        //         messages: [{
        //             key: Date.now().toString(),
        //             value: JSON.stringify(msg),
        //             partition: 0
        //         }]
        //     })
        // },5000)
    }

    onModuleDestroy() {

    }

    @Get("validate")
    validateGet(@Body() body) {
        console.log(body)
    }

    @Post("validate")
    validatePost(@Body() body) {
        body.MsgSeq = body.Data.CreateTime
        body.Data.MsgSeq = body.Data.CreateTime
        
        console.log(body)

        //发送到存储队列{
        this.producerGewe.send({
            topic: 'latestMsgToRedis',
            messages: [{
                key: Date.now().toString(),
                value: JSON.stringify(body),
                partition: 0
            }]
        })
    }
}